package org.example.config;

import org.example.exception.JwtInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class webConfig implements WebMvcConfigurer {
    @Resource
    private JwtInterceptor jwtInterceptor;
    @Value("${lqs.profile}")
    private String uploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 关键：将“虚拟访问路径 /profile/**”映射到“服务器真实存储路径 uploadPath”
        registry.addResourceHandler("/profile/**")
                .addResourceLocations("file:" + uploadPath + "/");
        // 例：若 uploadPath=D:/ruoyi/upload，那么访问 /profile/avatar/xxx.jpg → 实际读取 D:/ruoyi/upload/avatar/xxx.jpg
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")//拦截除了登录和注册的路径，要登录才能进
                .excludePathPatterns("/login", "/register","/profile/**");
    }


    /**
     * 跨域配置，保前端能 “成功发起请求” 到后端；
     * @return
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");//1 设置访问源地址 , 允许所有域名访问（生产环境需指定具体域名）
        config.addAllowedHeader("*");// 2 设置访问源请求头 ,允许所有请求头（如 Authorization、Content-Type）
        config.addAllowedMethod("*");// 3设置访问源请求方法,允许所有 HTTP 方法（GET、POST、PUT、DELETE 等）
        source.registerCorsConfiguration("/**", config); //对接口配置跨域设置// 对所有接口生效
        return new CorsFilter(source);
    }

}
